package com.xxxx.mail.listen;

import com.rabbitmq.client.Channel;
import com.xxxx.server.constant.MailConstants;
import com.xxxx.server.pojo.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @Author:王亚栋
 * @Date: 2023/6/20 下午9:45
 * @Version:1.0
 * 消息接收器
 */
@Component
@Slf4j(topic = "MailReceiver")
public class MailReceiver {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void Handler(Message message,
                        Channel channel){

        log.info("监听到{}对列中的消息了...",MailConstants.MAIL_QUEUE_NAME);

        Employee employee = (Employee) message.getPayload();

        MessageHeaders headers = message.getHeaders();
        //消息序号
        long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);

        String msgId = (String) headers.get("spring_returned_message_correlation");



        try {

            if (redisTemplate.opsForHash().entries("mail_log").containsKey(msgId)){

                log.error("消息已经被消费...=====>{}",msgId);

                /**
                 * 手动确认消息
                 * tag  消息序号
                 * multiple 是否确认多条
                 */
                channel.basicAck(tag,false);
            }

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);

            // 发件人
            helper.setFrom(mailProperties.getUsername());

            // 收件人
            helper.setTo(employee.getEmail());

            //主题
            helper.setSubject("入职欢迎邮件");

            //发送日期
            helper.setSentDate(new Date());

            // 邮件内容
            Context context = new Context();

            context.setVariable("name",employee.getName());

            context.setVariable("posName",employee.getPosition().getName());

            context.setVariable("joblevelName",employee.getJoblevel().getName());

            context.setVariable("departmentName",employee.getDepartment().getName());

            String mail = templateEngine.process("mail", context);

            helper.setText(mail,true);

            //发送邮件
            javaMailSender.send(mimeMessage);

            log.info("邮件发送成功！");

            //将消息Id 存入redis
            redisTemplate.opsForHash().put("mail_log",msgId,"OK");

            //手动确认消息
            channel.basicAck(tag,false);

        } catch (Exception e) {

            log.error("邮件发送失败！====={}",e.getMessage());
            //e.printStackTrace();

            log.error("消息已经被消费...=====>{}",msgId);

            /**
             * 手动确认消息
             * tag  消息序号
             * multiple 是否确认多条
             * requque 是否重回对列
             */
            try {
                channel.basicNack(tag,false,true);

            } catch (IOException ex) {

                log.error("邮件发送失败！====={}",e.getMessage());
            }
        }

    }

}
